package ua.kharkov.knure.pereverziev.diploma.web.command;

import java.io.IOException;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.Locale;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;

import ua.kharkov.knure.pereverziev.diploma.db.DAOServices.ServiceFactory;
import ua.kharkov.knure.pereverziev.diploma.db.entity.Ticket;

public class CheckOutCommand implements Command {

	private static final Logger log = Logger.getLogger(CheckOutCommand.class);

	@Override
	public String execute(final HttpServletRequest request,
			final HttpServletResponse response) throws IOException,
			ServletException {

		String forward = "/WEB-INF/jsp/error_page.jsp";

		final String cardType = request.getParameter("card_type");
		log.trace("Request parameter: card_type --> " + cardType);

		final String cardNumber = request.getParameter("card_number");
		// TODO REMOVE FROM THE PRODUCTION
		log.trace("Request parameter: card_number --> " + cardNumber);

		if (cardNumber != null) {

			DecimalFormat df = null;
			try {
				df = (DecimalFormat) NumberFormat.getInstance(Locale.US);
			} catch (ClassCastException e) {
				System.err.println(e);
			}

			df.applyPattern("####.00");

			final HttpSession session = request.getSession();

			final Ticket directTicket = (Ticket) session
					.getAttribute("directTicket");
			final Ticket returnTicket = (Ticket) session
					.getAttribute("returnTicket");

			float chargedMoney = 0;
			if (directTicket != null) {
				ServiceFactory.getInstance().getTicketService()
						.create(directTicket);
				chargedMoney += directTicket.getPrice();
				session.setAttribute("directTicket", null);
				log.debug("Direct ticket " + directTicket);
			}
			if (returnTicket != null) {
				ServiceFactory.getInstance().getTicketService()
						.create(returnTicket);
				chargedMoney += returnTicket.getPrice();
				session.setAttribute("returnTicket", null);
				log.debug("Return ticket " + returnTicket);
			}

			forward = "/WEB-INF/jsp/success.jsp?price="
					+ df.format(chargedMoney);
		}

		request.getSession().setAttribute("lastPage", forward);
		return forward;
	}
}
